package at.fhj.swd10.eshop.web.view;

import at.fhj.swd10.eshop.database.UserDao;
import at.fhj.swd10.eshop.domain.User;
import at.fhj.swd10.eshop.web.session.SessionBean;
import java.io.Serializable;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;

/**
 * @author David
 */
@ManagedBean
@ViewScoped
public class LoginBacking implements Serializable {

    @ManagedProperty(value = "#{sessionBean}")
    private SessionBean sessionBean;
    private UserDao userDao = UserDao.getUserDao();
    private String username;
    private String password;

    @PostConstruct
    public void init() {
        if (sessionBean.getUser() != null) {
            try {
                FacesContext.getCurrentInstance().getExternalContext().redirect("shoppingOverview.xhtml");
            } catch (Exception ex) {
            }
        }
    }

    public String login() throws Exception {
        User user = userDao.getUserByUsernameAndPassword(username, password);
        sessionBean.setUser(user);
        if (user == null) {
            FacesContext.getCurrentInstance().addMessage("login", new FacesMessage("login not successful - username or password wrong"));
            return "login";
        }
        return "shoppingOverview";
    }

    public SessionBean getSessionBean() {
        return sessionBean;
    }

    public void setSessionBean(SessionBean sessionBean) {
        this.sessionBean = sessionBean;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}
